/**
 * 
 */
package com.apesay.dao;

import com.apesay.utils.ApesayConstants;
import com.apesay.utils.DataUtils;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * 
 * ClassName: MongoDBConnection 
 * Reason: 修改mongodb数据库获取方式 
 * date: 2015年8月27日 上午10:34:56 
 *
 * @author sid
 */
public class MongoDBAuthConnection {

	protected static Logger logger = LoggerFactory.getLogger(MongoDBAuthConnection.class);

	private static MongoClient instance = null;

	protected static boolean isRenew = false;
	
	public static volatile boolean isShard = false;
	/**
	 * Mongodb连接实例
	 * 
	 * @return
	 */
	public synchronized static MongoClient getMongoClient() {
		if (instance != null) {
			return instance;
		}else{
			try {
				MongoClientOptions.Builder build = new MongoClientOptions.Builder();
				//build.autoConnectRetry(true);//是否连接自动重试
				build.connectionsPerHost(Integer.valueOf(ApesayConstants.mongodbConnectionsCount));//连接数
				build.connectTimeout(30000);//连接超时时间
				build.maxWaitTime(120000);//最大等待时间
				build.socketKeepAlive(true);//保持连接
				build.socketTimeout(0);//0，不限时间
				//build.maxAutoConnectRetryTime(1);//最大重试时间，单位秒
				build.threadsAllowedToBlockForConnectionMultiplier(50);
				MongoClientOptions mongoClientOptions = build.build();

				List<ServerAddress> addresses = new ArrayList<ServerAddress>();
				List<MongoCredential> auths = new ArrayList<MongoCredential>();
				if (DataUtils.isNotEmpty(ApesayConstants.mongoDBHOSTS)) {
					String[] hosts = ApesayConstants.mongoDBHOSTS.split(",");
					String[] ports = ApesayConstants.momgoDBPORTS.split(",");
					for (int i = 0; i < hosts.length; i++) {
						ServerAddress address = new ServerAddress(hosts[i], Integer.valueOf(ports[i]));
						addresses.add(address);
					}
					MongoCredential cc = MongoCredential.createCredential(ApesayConstants.mongoDBUser
							, ApesayConstants.mongoDBName, ApesayConstants.mongoDBPassword.toCharArray());
					auths.add(cc);
					instance = new MongoClient(addresses, auths, mongoClientOptions);
					MongoDBAuthConnection.isShard = true;
				}else{
					ServerAddress address = new ServerAddress(ApesayConstants.mongoDBIP, Integer.valueOf(ApesayConstants.mongoDBPORT));
					MongoCredential cc = MongoCredential.createCredential(ApesayConstants.mongoDBUser
							, ApesayConstants.mongoDBName, ApesayConstants.mongoDBPassword.toCharArray());
					auths.add(cc);
					instance = new MongoClient(address, auths);
					MongoDBAuthConnection.isShard = false;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
				logger.error("Mongon数据库服务器连接失败！", e);
			}
		}
		return instance;
	}
}
